package leetcode.code1721;

import leetcode.IDebug;
import leetcode.helper.tree.ListNode;

public class Solution implements IDebug {

	public ListNode swapNodes(ListNode head, int k) {
		ListNode root = new ListNode();
		root.next = head;
		int k1 = k - 1;// 正数第k的前一个
		int k2 = k + 1;// 倒数第k的前一个
		ListNode p1 = root;
		ListNode p2 = root;
		ListNode p = root;
		int cnt = 0;
		while (p != null) {
			if (cnt == k1) {
				p1 = p;
			}
			p = p.next;
			cnt++;
			if (cnt > k2) {
				p2 = p2.next;
			}
		}
		ListNode lk2 = p2.next;
		ListNode lk1 = p1.next;
		if (lk2 == lk1) {
			return root.next;
		} else if (lk1.next == lk2) {
			p1.next = lk2;
			lk1.next = lk2.next;
			lk2.next = lk1;
		} else if (lk2.next == lk1) {
			p2.next = lk1;
			lk2.next = lk1.next;
			lk1.next = lk2;
		} else {
			p2.next = lk2.next;
			p1.next = lk1.next;
			lk1.next = p2.next;
			p2.next = lk1;
			lk2.next = p1.next;
			p1.next = lk2;
		}
		return root.next;
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug3() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug2() {
		// TODO Auto-generated method stub

	}

	@Override
	public void debug1() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();

	}

}
